﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WQLWebAPI.Api.Filters
{
    public class LoggerAttribute : ActionFilterAttribute
    {
        private string Arguments;

        public string Operation { get; set; }
        public override void OnResultExecuted(ResultExecutedContext context)
        {
            var _logger = context.HttpContext.RequestServices.GetService(typeof(ILogger<LoggerAttribute>)) as ILogger;
            var username = context.HttpContext.User.Claims.FirstOrDefault(d => d.Type == "name");
            var ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
            var responseCode = context.HttpContext.Response.StatusCode;

            _logger.LogInformation("{Username};{Operation};{Arguments};{Ip};{Code};{Date}", username == null ? "null" : username.Value, Operation, Arguments, ip, responseCode, DateTime.Now);
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {

            Arguments = JsonConvert.SerializeObject(context.ActionArguments);

        }


    }
}
